package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Date:2023/7/6
 * Author:丐版小杨哥
 * Description:
 */
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    /**
     * 课程分类的分层查询
     * @return
     */
    @Override
    public List<CourseCategoryTreeDto> queryTreeNode(String id) {
        //获取所有节点数据
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //转为map集合去掉1节点
        Map<String, CourseCategoryTreeDto> tempMap = courseCategoryTreeDtos.stream().
                filter(item -> !item.getId().equals(id)).
                collect(Collectors.toMap(key -> key.getId(),value -> value,(key1, key2)-> key2));
        //目标返回值
        ArrayList<CourseCategoryTreeDto> courseCategoryTreeList = new ArrayList<>();
        //分离出子节点父节点把子节点存储到父节点中
        courseCategoryTreeDtos.stream().forEach(item->{
            if (item.getParentid().equals(id)){
                courseCategoryTreeList.add(item);
            }
            CourseCategoryTreeDto parentNode = tempMap.get(item.getParentid());
            if (parentNode!=null){
                if (parentNode.getChildrenTreeNodes()==null){
                    parentNode.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                parentNode.getChildrenTreeNodes().add(item);
            }
        });
        return courseCategoryTreeList;
    }
}